package com.mvu.banana.internal.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.mvu.banana.common.client.CommonComposite;
import com.mvu.banana.common.client.UiIn;
import com.mvu.banana.common.client.UiOut;
import com.mvu.banana.common.widget.AutoCompleteTextBox;
import com.mvu.banana.common.widget.SimpleAutoCompletionItems;
import com.mvu.banana.internal.generated.RunBoxDTO;
import org.hibernate.validator.constraints.Length;

/**
 * Created by mvu at 5/28/11 11:26 AM
 * To change this template use File | Settings | File Templates.
 */
public class RunBox extends CommonComposite {
  interface RunBoxUiBinder extends UiBinder<VerticalPanel, RunBox> {
  }

  private static RunBoxUiBinder ourUiBinder = GWT.create(RunBoxUiBinder.class);
  @UiIn
  @UiField
  @Length(min = 1, max = 100)
  public AutoCompleteTextBox input;
  @UiField
  @UiOut
  public
  TextArea console;

  public RunBox() {
    super(new RunBoxDTO());
    initWidget(ourUiBinder.createAndBindUi(this));
  }

  @UiOut
  public void setSuggestions(String[] suggestions){
    input.setCompletionItems(new SimpleAutoCompletionItems(suggestions));
  }

  @Override
  protected void onLoad() {
    super.onLoad();
    input.setFocus(true);
    get();
  }

  @UiHandler("input")
  public void onKeyDown(KeyDownEvent event) {
    int code = event.getNativeKeyCode();
    if(KeyCodes.KEY_ESCAPE == code){
      String text = input.getText();
      int i = text.lastIndexOf(' ');
      if(i == -1){
        i = 0;
      }
      input.setText(text.substring(0, i));
      get();
    }else if(KeyCodes.KEY_TAB == code){
      event.preventDefault(); // do not tab out
    }
  }

  @UiHandler("input")
  public void onKeyUp(KeyUpEvent event) {
    int code = event.getNativeKeyCode();
    if(code == 32 || code == KeyCodes.KEY_ENTER){
      // space
      get();
    }
  }
}